from django.db import transaction
from rest_framework.views import APIView
from apps.system.models import Upload
from apps.system.serializers import UploadSerializer
from utils import response_error, response_ok
from utils.customer_modelviewset import CustomModelViewSet


class UploadFileViewSet(APIView):

    def post(self, request):
        type = request.data.get('type', 'others')
        file = request.FILES.get('file')
        if not file:
            return response_error(u'未找到上传的数据')
        try:
            with transaction.atomic():
                upload = Upload.objects.upload(file, type)
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))
        return response_ok(upload.id)


class UploadViewSet(CustomModelViewSet):
    queryset = Upload.objects.filter()
    serializer_class = UploadSerializer

    def create(self, request, *args, **kwargs):
        file = request.FILES.get('file')
        if not file:
            return response_error(u'未找到上传的数据')
        try:
            with transaction.atomic():
                upload = Upload.objects.upload(file, Upload.OTHERS)
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))
        return response_ok()
